let config = require("../config");
let service = require("../service");
let materialColors = config.materialColors;
function createRecyclerViewAdapter(items, onBindViewHolder) {
  let itemLayout = (
    <horizontal gravity="center_vertical" marginBottom="16">
      <View id="side" h="*" w="10" />
      <text id="content" marginLeft="16" textSize="16sp" textColor="#ffffff"></text>;
    </horizontal>
  );

  return RecyclerView.Adapter({
    onCreateViewHolder: function (parent, viewType) {
      // log("onCreateViewHolder");
      // 视图创建
      let view;
      let holder;
      view = ui.inflate(itemLayout, parent, false);
      holder = JavaAdapter(RecyclerView.ViewHolder, {}, view);
      view.click(function () {
        let item = items[holder.getAdapterPosition()];
        if (item.repoUrl) {
          // https://gitee.com/yashujs/Gitee.VisualStudio
          // 提取owner
          let reg = /gitee.com\/(.*)\/(.*)/;
          let match = item.repoUrl.match(reg);
          if (match) {
            let owner = match[1];
            let repo = match[2];
            let token = config.storage.get("token", false);
            let url = "https://gitee.com/api/v5/repos/" + owner + "/" + repo + "/branches/master?access_token=" + token;
            http.get(url, {}, function (res, err) {
              if (err) {
                console.error(err);
                return;
              }
              if (res.statusCode == 404) {
                toastLog("仓库不存在");
              } else {
                toastLog("仓库存在");

                engines.execScriptFile("page/repo-detail.js", { arguments: { repoUrl: item.repoUrl } });
              }
            });
          }
        }
      });
      return holder;
    },
    onBindViewHolder: onBindViewHolder,
    getItemCount: function () {
      return items.length;
    },
  });
}
(function () {
  util.extend(CustomView, ui.Widget);
  function CustomView() {
    ui.Widget.call(this);
    this.title = "";
    this.data = [1, 2, 3];
    this.requestData = function () {
      return [];
    };
    this.moreMenuAction = function () {};
  }
  CustomView.prototype.searchAction = function () {
    // 运行搜索仓库界面
    engines.execScriptFile("page/search.js");
  };
  CustomView.prototype.render = function () {
    return (
      <vertical padding="16">
        <frame marginBottom="16">
          <img
            id="moreMenus"
            tint="#ffffff"
            src="@drawable/ic_menu_black_48dp"
            layout_gravity="center_vertical"
            w="40dp"
          ></img>
          <TextView
            id="title"
            textColor="#ffffff"
            textSize="32sp"
            layout_width="wrap_content"
            layout_height="wrap_content"
            layout_centerInParent="true"
            layout_gravity="center"
            text="动态"
          />
          <img
            id="search"
            tint="#ffffff"
            src="@drawable/ic_search_black_48dp"
            layout_gravity="right|center"
            w="40dp"
          ></img>
        </frame>

        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
          id="swipeRefreshLayout"
          layout_width="match_parent"
          layout_height="wrap_content"
        >
          <androidx.recyclerview.widget.RecyclerView
            id="recyclerView"
            layout_width="match_parent"
            layout_height="match_parent"
          />
        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
      </vertical>
    );
  };
  CustomView.prototype.setTitle = function (title) {
    this.title = title;
  };
  CustomView.prototype.refresh = function (updateData) {
    service.getUserEvents(updateData);
  };
  CustomView.prototype.setData = function (data) {
    this.data = data;
  };
  CustomView.prototype.setBindViewHolder = function (bindViewHolder) {
    this.bindViewHolder = bindViewHolder;
  };
  CustomView.prototype.getBindViewHolder = function (data) {
    return this.bindViewHolder(data);
  };
  CustomView.prototype.setRequestData = function (requestData) {
    this.requestData = requestData;
  };
  CustomView.prototype.init = function (view) {
    view.swipeRefreshLayout.setRefreshing(true);
    let timeoutID = setTimeout(() => {
      view.swipeRefreshLayout.setRefreshing(false);
    }, 3000);
    let that = this;
    this.requestData()
      .then((items) => {
        var len = items.length;
        for (var i = 0; i < len; i++) {
          let item = items[i];
          item.color = materialColors[i % materialColors.length];
        }
        // log(items[0]);
        view.swipeRefreshLayout.setRefreshing(false);
        // 终止timeout
        clearTimeout(timeoutID);
        let onBindViewHolder = this.getBindViewHolder(items);
        let recycleAdapter = createRecyclerViewAdapter(items, onBindViewHolder);
        ui.run(function () {
          view.recyclerView.setAdapter(recycleAdapter);
        });
      })
      .catch((error) => {
        log(error);

        view.swipeRefreshLayout.setRefreshing(false);
        clearTimeout(timeoutID);
        let onBindViewHolder = this.getBindViewHolder(this.data);
        let recycleAdapter = createRecyclerViewAdapter(items, onBindViewHolder);
        ui.run(function () {
          view.recyclerView.setAdapter(recycleAdapter);
        });
      });
  };

  CustomView.prototype.setMoreMenuAction = function (action) {
    this.moreMenuAction = action;
  };
  CustomView.prototype.onViewCreated = function (view) {};
  CustomView.prototype.onFinishInflation = function (view) {
    view.swipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED);
    // 设置布局管理器
    let layoutManager = new LinearLayoutManager(context);
    view.recyclerView.setLayoutManager(layoutManager);
    let that = this;
    ui.post(function () {
      view.title.setText(that.title);
      that.init(view);
    }, 200);

    view.swipeRefreshLayout.setOnRefreshListener(
      new SwipeRefreshLayout.OnRefreshListener({
        onRefresh: function () {
          com.google.android.material.snackbar.Snackbar.make(view.swipeRefreshLayout, "数据请求中", 2000).show();
          that.init(view);
          return;
        },
      })
    );
    view.moreMenus.click(function () {
      that.moreMenuAction();
    });
    view.search.click(function () {
      that.searchAction();
    });
  };

  ui.registerWidget("data-show", CustomView);
  return CustomView;
})();
